package com.yu.demo.user.domain.service;

import com.yu.demo.user.domain.entity.User;
import com.yu.demo.user.domain.repository.UserRepository;
import com.yu.demo.user.domain.valueobject.Email;
import com.yu.demo.user.domain.valueobject.Username;
import org.springframework.stereotype.Service;

/**
 * 用户领域服务实现
 * 实现跨实体的业务逻辑和复杂的业务规则
 */
@Service
public class UserDomainServiceImpl implements UserDomainService {
    
    private final UserRepository userRepository;
    
    public UserDomainServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @Override
    public boolean isUsernameUnique(Username username) {
        return !userRepository.existsByUsername(username);
    }
    
    @Override
    public boolean isEmailUnique(Email email) {
        return !userRepository.existsByEmail(email);
    }
    
    @Override
    public boolean canRegister(User user) {
        // 检查用户名和邮箱的唯一性
        return isUsernameUnique(user.getUsername()) && isEmailUnique(user.getEmail());
    }
    
    @Override
    public boolean canLogin(User user) {
        // 用户必须存在且处于激活状态
        return user != null && user.isActiveUser();
    }
    
    @Override
    public boolean canUpdateProfile(User user, Username newUsername, Email newEmail) {
        if (user == null) {
            return false;
        }
        
        // 如果用户名发生变化，检查新用户名的唯一性
        if (newUsername != null && !user.getUsername().equals(newUsername)) {
            if (!isUsernameUnique(newUsername)) {
                return false;
            }
        }
        
        // 如果邮箱发生变化，检查新邮箱的唯一性
        if (newEmail != null && !user.getEmail().equals(newEmail)) {
            if (!isEmailUnique(newEmail)) {
                return false;
            }
        }
        
        return true;
    }
    
    @Override
    public boolean canChangeRole(User currentUser, User targetUser, String newRole) {
        // 只有管理员可以更改用户角色
        if (currentUser == null || !currentUser.isAdmin()) {
            return false;
        }
        
        // 不能更改自己的角色
        if (currentUser.getId().equals(targetUser.getId())) {
            return false;
        }
        
        // 目标用户必须存在且激活
        if (targetUser == null || !targetUser.isActiveUser()) {
            return false;
        }
        
        return true;
    }
}
